package com.yinshan.arface;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yinshan.arface.utils.FaceUtils;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author limh
 * @function 人脸采集
 * @date 2019/3/28 11:01
 */
public class FaceVerifyActivity extends AppCompatActivity implements View.OnClickListener {

    //开始录制
    private final int RECORD_START = 1000;
    //提示眨眼
    private final int RECORD_BLINK = 1002;
    //采集完成
    private final int RECORD_COMPLETE = 1003;


    private TextView txtHint;
    private ImageView imgPlay;
    private ImageView imgConfirm;
    private ImageView imgAgain;
    private ProgressBar progressBar;
    private FaceView sufaceView;

    private Context context;
    private Chronometer chronometer;
    private int PREVIEW_WIDTH = 640;
    private int PREVIEW_HEIGHT = 480;

    //缩略图
    private String thumbnail;
    private boolean isPlay = false;
    private boolean isRecord = false;
    //录制定时器
    private Timer timer;
    private Vibrator vibrator;

    //初始倒计时
    private CountDownTimer downTimer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarFullTransparent();
        setContentView(R.layout.activity_face_verify);
        context = new WeakReference<Activity>(this).get();
        initView();
    }

    private void initView() {
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        txtHint = findViewById(R.id.txt_face_hint);
        imgPlay = findViewById(R.id.img_face_status);
        imgPlay.setOnClickListener(this);
        imgConfirm = findViewById(R.id.img_face_confirm);
        imgConfirm.setOnClickListener(this);
        imgAgain = findViewById(R.id.img_face_again);
        imgAgain.setOnClickListener(this);
        chronometer = findViewById(R.id.chronometer);
        sufaceView = findViewById(R.id.surface_view);
        progressBar = findViewById(R.id.progress);
        String productName = getIntent().getStringExtra("productName");
        if (!TextUtils.isEmpty(productName)) {
            TextView txtProduct = findViewById(R.id.txt_face_tab);
            txtProduct.setVisibility(View.VISIBLE);
            txtProduct.setText(String.format("“%s”无手续费、中介费，未与任何其他机构合作", productName));
        }
        findViewById(R.id.img_face_close).setOnClickListener(this);
        FaceUtils.getInstance(context).createRecordDir();
        setSurfaceSize();
        downTimer = new CountDownTimer(6000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                String html = String.format(Locale.CHINA, "<font color=\"#ff4600\">%d</font>秒后开始人脸识别，也可直接点击开始按钮", millisUntilFinished / 1000);
                txtHint.setText(Html.fromHtml(html));
            }

            @Override
            public void onFinish() {
                if (null != vibrator) {
                    vibrator.vibrate(200);
                }
                txtHint.setText("请正对手机 将脸部置于界面方框中");
                imgPlay.performClick();
            }
        };
        downTimer.start();
    }

    /**
     * 设置计时器
     */
    public void initData() {
        chronometer.setBase(SystemClock.elapsedRealtime());//计时器清零
        chronometer.setFormat("%s"); // 00：00
    }

    private void setSurfaceSize() {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int width = metrics.widthPixels;
        int height = (int) (width * PREVIEW_WIDTH / (float) PREVIEW_HEIGHT);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
        params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        sufaceView.setLayoutParams(params);
    }

    protected void setStatusBarFullTransparent() {
        if (Build.VERSION.SDK_INT >= 21) {//21表示5.0
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= 19) {//19表示4.4
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.img_face_status) {
            if (null != downTimer) {
                downTimer.cancel();
            }
            if (isRecord) return;
            isPlay = !isPlay;
            if (isPlay) {
                txtHint.setBackgroundResource(R.drawable.shape_face_hint_bg);
                imgPlay.setImageResource(R.drawable.ic_face_pause);
                handler.sendEmptyMessage(RECORD_START);
            }
        } else if (i == R.id.img_face_confirm) {
            Intent intent = new Intent();
            File file = FaceUtils.getInstance(context).getmVecordFile();
            if (null != file) {
                intent.putExtra("video", FaceUtils.getInstance(context).getmVecordFile().getAbsolutePath());
            }
            if (!TextUtils.isEmpty(thumbnail)) {
                intent.putExtra("thumbnail", thumbnail);
            }
            setResult(RESULT_OK, intent);
            finish();
        } else if (i == R.id.img_face_again) {
            FaceUtils.getInstance(context).delFile();
            FaceUtils.getInstance(context).doOpenCamera(sufaceView.getSurfaceHolder(), Camera.CameraInfo.CAMERA_FACING_FRONT);
            FaceUtils.getInstance(context).doStartPreview(sufaceView.getSurfaceHolder(), 1.333f);
            initData();
            showView(false);
            txtHint.setText("请点击开始按钮，开始人脸信息采集");
        } else if (i == R.id.img_face_close) {
            finish();
        }
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            String txt_hint_str2 = "请正对手机 将脸部置于界面方框中";
            String txt_hint_str3 = "正在采集请眨眼";
            String txt_hint_str4 = "采集完成，请点击右下角“√”按钮";
            switch (msg.what) {
                //开始采集
                case RECORD_START:
                    chronometer.start();
                    txtHint.setText(txt_hint_str2);
                    try {
                        Camera mCamera = FaceUtils.getInstance(context).getCameraInstance();
                        if (mCamera != null) {
                            mCamera.unlock();
                        }
                        // 准备录制视频
                        FaceUtils.getInstance(context).initRecord(sufaceView);
                        startRecord(); // 开始录制视频
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    showView(false);
                    break;
                //采集完成
                case RECORD_COMPLETE:
                    txtHint.setText(txt_hint_str4);
                    if (null != chronometer) {
                        chronometer.stop();
                    }
                    initData();
                    stop();
                    showView(true);
                    thumbnail = FaceUtils.getThumbnail(context);
                    break;
                //提示眨眼
                case RECORD_BLINK:
                    if (null != vibrator) {
                        vibrator.vibrate(200);
                    }
                    txtHint.setText(txt_hint_str3);
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    private int mTimeCount;
    private int mRecordMaxTime = 7;

    /**
     * 开始录制视频
     */
    public void startRecord() {
        isRecord = true;
        initData();
        try {
            mTimeCount = 0;
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    progressBar.setProgress(100 * mTimeCount / mRecordMaxTime);
                    if (mTimeCount == mRecordMaxTime) {// 达到指定时间，停止拍摄
                        // 显示发送，重拍按钮
                        handler.sendEmptyMessage(RECORD_COMPLETE);
                    } else if (mTimeCount == 3) {
                        // 提示眨眼
                        handler.sendEmptyMessage(RECORD_BLINK);
                    }
                    mTimeCount++;
                }
            }, 0, 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止拍摄
     */
    public void stop() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        isPlay = false;
        isRecord = false;
        imgPlay.setImageResource(R.drawable.ic_face_play);
        FaceUtils.getInstance(context).stopRecord();
        FaceUtils.getInstance(context).releaseRecord();
        FaceUtils.getInstance(context).doDestroyCamera();
        FaceUtils.getInstance(context).doDestroyCameraInterface();
    }

    @Override
    public void onPause() {
        super.onPause();
        isPlay = false;
        isRecord = false;
        FaceUtils.getInstance(context).stopRecord();
        FaceUtils.getInstance(context).releaseRecord();
        FaceUtils.getInstance(context).doDestroyCamera();
    }

    /**
     * 更新底部重新开始按钮
     *
     * @param show 是否显示
     */
    private void showView(boolean show) {
        imgConfirm.setVisibility(show ? View.VISIBLE : View.INVISIBLE);
        imgAgain.setVisibility(show ? View.VISIBLE : View.INVISIBLE);
        imgPlay.setVisibility(show ? View.INVISIBLE : View.VISIBLE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FaceUtils.getInstance(context).doDestroyCamera();
        this.context = null;
        chronometer = null;
        if (null != vibrator) {
            vibrator.cancel();
            vibrator = null;
        }
        if (null != downTimer) {
            downTimer.cancel();
            downTimer = null;
        }
    }
}
